<template>
  <div class="app-container">
    <el-form :inline="true" ref="queryRef" label-position="right" :model="params" label-width="200px" :rules="rules">
      <div class="form-inline">
        <el-row justify="center">
          <el-col :span="11">
            <el-form-item label="区划代码：" class="form-item" prop="zoningCode">
              <el-input v-model="params.zoningCode" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="变更原因：" class="form-item" prop="reasonForChange">
              <el-input v-model="params.reasonForChange" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="center">
          <el-col :span="11">
            <el-form-item label="经度:" class="form-location">
              <el-col :span="11">
                <el-form-item prop="startLongitude">
                  <el-input v-model="params.startLongitude" placeholder="请输入" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
              <el-col :span="11">
                <el-form-item prop="endLongitude">
                  <el-input v-model="params.endLongitude" placeholder="请输入" clearable />
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="纬度:" class="form-location">
              <el-col :span="11">
                <el-form-item prop="startLatitude">
                  <el-input v-model="params.startLatitude" placeholder="请输入" clearable />
                </el-form-item>
              </el-col>
              <el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
              <el-col :span="11">
                <el-form-item prop="endLatitude">
                  <el-input v-model="params.endLatitude" placeholder="请输入" clearable />
                </el-form-item>
              </el-col>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row justify="center">
          <el-col :span="11">
            <el-form-item label="区域：" prop="region">
              <el-form-item prop="province" style="width:120px;margin-right:10px;">
                <el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince" clearable value-key="id">
                  <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="city" style="width:120px;margin-right:10px;">
                <el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable value-key="id">
                  <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="county" style="width:120px;">
                <el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable value-key="id">
                  <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-form-item>
          </el-col>
          <el-col :span="11"></el-col>
        </el-row>
        <el-row justify="end">
          <el-form-item class="bottom-button">
            <el-button type="primary" @click="onDelete">删除</el-button>
            <el-button type="primary" @click="onImportParms">导入</el-button>
            <el-button type="primary" @click="onButtonSearch">查询</el-button>
            <el-button type="primary" @click="onRest">重置</el-button>
            <el-button type="primary" @click="onExport">导出</el-button>
            <el-button type="primary" @click="onAdd">新设</el-button>
          </el-form-item>
        </el-row>
      </div>
    </el-form>

    <el-tabs v-model="activeName" type="card" class="demo-tabs" @tab-click="handleClickTab">
      <el-tab-pane label="列表展示" name="first">
        <div class="table-wrapper"></div>
      </el-tab-pane>
      <el-tab-pane label="变更列表" name="second"></el-tab-pane>
      <el-tab-pane label="变更后列表" name="third"></el-tab-pane>
      <el-tab-pane label="地图展示" name="fourth">
        <!--地图-->
        <GroundMotionParamManageMap v-show="activeName=='fourth'" :dataList="mapDataList" ref="mapRefQHT" @getResultsByGeomText="getResultsByGeomText" @mapLoading="mapLoading"></GroundMotionParamManageMap>
      </el-tab-pane>
    </el-tabs>
    <!-- 表格 -->
    <div v-if="activeName !== 'fourth'">
      <el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
        @selection-change="handleSelectionChange" :cell-style="{ border: '1px solid #e5ebf7' }"
        :header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
        <el-table-column v-if="activeName === 'first'" type="selection" width="55" label="序号" />
        <el-table-column prop="gmpCode" header-align="center" align="center" label="编码" width="160">
          <template #default="scope">
            <el-button link type="text" size="small" @click.prevent="viewProject(scope.row)">{{scope.row.gmpCode}}</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="id" header-align="center" align="center" label="ID" />
        <el-table-column prop="zoningCode" header-align="center" align="center" label="区划代码" />
        <el-table-column prop="province" header-align="center" align="center" label="省" />
        <el-table-column prop="city" header-align="center" align="center" label="市" />
        <el-table-column prop="county" header-align="center" align="center" label="县" />
        <el-table-column v-if="activeName === 'first'" prop="township" header-align="center" align="center" label="乡镇" />
        <el-table-column prop="longitude" header-align="center" align="center" label="经度" />
        <el-table-column prop="latitude" header-align="center" align="center" label="纬度" />
        <el-table-column prop="peakAcceleration" header-align="center" align="center" label="峰值加速度/g" />
        <el-table-column prop="responseSpectrum" header-align="center" align="center" label="反应谱特征周期／s：" width="160" />
        <el-table-column v-if="activeName === 'second' || activeName === 'third'" prop="reasonForChange"
          header-align="center" align="center" label="变更原因" />
        <el-table-column v-if="activeName === 'second' || activeName === 'third'" prop="approvalDocuments"
          header-align="center" align="center" label="批准文件" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="onDemolition(scope.row)">撤设</el-button>
            <el-button v-if="scope.row.originalId !== null" type="text" size="small" @click="onRestore(scope.row)">恢复</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="paging">
        <el-pagination background v-model:current-page="pagination.pageNo" :layout="layout"
          :page-size="pagination.pageSize" :total="pagination.total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange" />
      </div>
    </div>
    <!-- 地图 -->
    <div v-else></div>

    <!-- 导入数据 -->
    <ImportData v-if="dialogVisible" v-model="dialogVisible" ref="uploadRef" :downloadFileName="downloadFileName"
      :uploadUrl="uploadFileUrl" @importSuccess="onImport"></ImportData>
  </div>
</template>

<script setup>
//地图
import GroundMotionParamManageMap from '@/map/groundMotionParamManage/map.vue';
import { queryResultsByGeomText } from "@/api/groundMotionParamManage/groundMotionParamManage.js";
import { reactive, toRefs, ref, onMounted, getCurrentInstance } from "vue";
// 引入省份和获取下级区域
import { getProvince, getChildArea } from '@/api/system/division';
// 引入文档下载接口
import { downloadGet } from '@/utils/request';
// 引入数据导入弹框组件
import ImportData from '@/components/ImportData';
// 引入表单验证
import { validateLon, validateLat } from '@/components/FormValidate';
// 引入接口
import {
  queryMotionParameters, //分页
  deleteData //删除
} from '@/api/groundMotionParamManage/groundMotionParamManage.js';

// 当前对象实例
const { proxy } = getCurrentInstance();
// 全局路由对象
const router = useRouter();
//tab切换选中
const activeName = ref("first");


// tab切换
function handleClickTab(tab) {
  // console.log(tab.index); // 下标
  // console.log(tab.active); // 选中状态
  // console.log(tab.paneName); // 选中状态
  activeName.value = tab.paneName;
  // 注意：切换tab时，要将页码显示到第一页，每页显示行数默认为10条
  pagination.value.pageNo = 1;
  pagination.value.pageSize = 10;

  if(activeName.value=="fourth"&&isRefesh.value) {
    isRefesh.value=false;
    proxy.$refs['mapRefQHT'].switchTabQHTMap();
  }

  // 加载表格
  if(activeName.value=="first"||activeName.value=="second"||activeName.value=="third") {
    onSearch();//todo:复制一个新的方法，与按钮操作区分开。
  }
}

// 文件上传
// 文件上传弹框组件对象
const uploadRef = ref();
// 是否显示弹框组件
const dialogVisible = ref(false);
// 上传地址
const uploadFileUrl = '/groundMotionParameters/importData';
// 模板文件名称
const downloadFileName = '地震动参数城镇列表.xlsx';
// 上传完成回调
const onImport = (response, uploadFile, uploadFiles) => {
  // console.log(response.message);
}

// 定义变量
const data = reactive({
  // 表单参数
  params: {
    zoningCode: "", //区划代码
    reasonForChange: "",	//变更原因
    province: "", //省
    city: "",//市
    county: "",//县
    township: "",//乡镇
    startLongitude: "",//开始经度
    endLongitude: "",	//结束经度
    startLatitude: "",//开始纬度
    endLatitude: "",//结束纬度
    listType: "",
  },
  rules: {
    startLongitude: [
      { message: "请输入开始经度", trigger: "blur" },
      {
        validator: validateLon,
        trigger: ["change", "blur"],
      },
    ],
    endLongitude: [
      { message: "请输入结束经度", trigger: "blur" },
      {
        validator: validateLon,
        trigger: ["change", "blur"],
      },
    ],
    startLatitude: [
      { message: "请输入开始纬度", trigger: "blur" },
      {
        validator: validateLat,
        trigger: ["change", "blur"],
      },
    ],
    endLatitude: [
      { message: "请输入结束纬度", trigger: "blur" },
      {
        validator: validateLat,
        trigger: ["change", "blur"],
      },
    ]

  },

  // 表格
  tableData: [],
  // 分页，控件
  layout: " prev, pager, next, jumper, sizes, total",
  // 分页，参数
  pagination: {
    pageNo: 1,
    pageSize: 10,
    total: 100,
  },
});
const {
  params,
  pagination,
  layout,
  rules,
  tableData
} = toRefs(data);

// 行政区划
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
/** 获取省列表 */
function getProvinceData() {
  getProvince().then(response => {
    provinceData.value = response.data;
  });
}
// 选择省份
function chooseProvince(value) {
  params.value.city = null;
  params.value.county = null;
  params.value.province = value.name;
  cityData.value = [];
  areaData.value = [];
  // 下级区域
  getChildArea(value.id).then(response => {
    cityData.value = response.data;
  });
}
// 选择城市
function chooseCity(value) {
  params.value.city = value.name;
  params.value.county = null;
  areaData.value = [];
  getChildArea(value.id).then(response => {
    areaData.value = response.data;
  });
}
// 选择区县
function chooseCounty(value) {
  params.value.county = value.name;
}

// 表格对象
const multipleTableRef = ref();
// 当前选中行
const curTableRow = ref(null);
// 表格行多选
const multipleSelection = ref([]);
// 表格行选中事件
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  // 当前行
  curTableRow.value = val;
};
// 分页，修改当前页数事件
const handleCurrentChange = (val) => {
  pagination.value.pageNo = val;
  // 查询
  onSearch();
};
// 分页，修改每页显示行数事件
const handleSizeChange = (val) => {
  pagination.value.pageSize = val;
  // 当前页数置1
  pagination.value.pageNo = 1;
  // 查询
  onSearch();
};

// 点击编号跳转至此数据的详细信息界面
const viewProject = row => {
  router.push({ path: '/groundMotionParamManage/queryDetails', query: { gmpId: row.gmpId } });
};
//撤设
const onDemolition = row => {
  router.push({
    path: '/groundMotionParamManage/queryDetails', query: { gmpId: row.gmpId, type: 'demolition' }
  });
};
//恢复
const onRestore = row => {
  router.push({
    path: '/groundMotionParamManage/queryDetails', query: {
      gmpId: row.gmpId,
      originalId: row.originalId,
      approvalDocuments: row.approvalDocuments,
      reasonForChange: row.reasonForChange,
      type: 'restore'
    }
  });
};

// 批量删除
const onDelete = () => {
  if (!multipleSelection.value || multipleSelection.value.length <= 0) {
    proxy.$modal.msgWarning('请选中数据!');
    return false;
  }
  proxy.$modal.confirm('确认删除数据, 是否继续?').then(async () => {
    let ids = []
    multipleSelection.value.forEach(item => {
      ids.push(item.gmpId)
    })
    const paramsp = { ids: ids.join(",") }
    deleteData(paramsp).then((res) => {
      if (res.code === 200) {
        proxy.$modal.msgSuccess('删除成功!');
        //查询
        onSearch();
      }
    }).catch(err => {
      proxy.$modal.msgError('删除失败!');
    })
  }).catch((error) => {
    proxy.$modal.msg('已取消删除!');
  })
}
// 导入
const onImportParms = (val) => {
  dialogVisible.value = true;
}

//张平修改
const isRefesh = ref(true);
/*const handleClick = (tab, event) => {
  if(activeName.value=="second"&&isRefesh.value) {
    isRefesh.value=false;
    console.log(proxy.$refs['mapRefQPXM'],'===')
    proxy.$refs['mapRefQPXM'].switchTabQPXMMap();
  }
}*/

const lastSearchParams=ref({});
const currentGemo=ref();
const searchGemo=ref();

//张平修改

const getListAndMapData = ()=>{
  let listType = null
  if (activeName.value === 'first') {
    listType = 0
  } else if (activeName.value === 'second') {
    listType = 1
  }
  if(listType==null&&activeName.value === 'fourth'){
    searchGemo.value=currentGemo.value;
    const query = {
      ...lastSearchParams.value,
      geom: currentGemo.value,
    }
    mapLoading(true);
    //地图圈选查询
    queryResultsByGeomText(query).then((res) => {
      if (res.code === 200) {
        mapDataList.value = res.data;
        if(res.data!=null && res.data.length>0){
          let length = res.data.length;
          // proxy.$modal.msgSuccess("查询到"+length+"条数据.");
        }else{
          proxy.$modal.msgWarning('圈选范围无查询结果！');
        }
      }else{
        proxy.$modal.msgWarning('查询失败！');
      }
      mapLoading(false);
    }).catch(err => {
      console.log(err);
      proxy.$modal.msgError('查询失败！');
      mapLoading(false);
    });
  }else{
    searchGemo.value=null;
  }
  queryMotionParameters({
    ...lastSearchParams.value,
    page: pagination.value.pageNo,
    rows: pagination.value.pageSize,
    listType: listType,
    geom:searchGemo.value
  }).then(res => {
    if (res.code === 200 && res.data) {
      // 分页总数
      pagination.value.total = res.data.total;
      tableData.value = res.data.rows.length ? res.data.rows : [];
    } else {
      // 分页总数
      pagination.value.total = 0;
      tableData.value = [];
    }
  }).catch(err => {
    console.log(err);
  });
};

const onButtonSearch = () => {
  lastSearchParams.value=JSON.parse(JSON.stringify(params.value));
  getListAndMapData();
};

// 查询
const onSearch = () => {
  getListAndMapData();
  /*let listType = null
  if (activeName.value === 'first') {
    listType = 0
  } else if (activeName.value === 'second') {
    listType = 1
  }
  queryMotionParameters({
    ...lastSearchParams.value,
    page: pagination.value.pageNo,
    rows: pagination.value.pageSize,
    listType: listType
  }).then(res => {
    if (res.code === 200 && res.data) {
      // 分页总数
      pagination.value.total = res.data.total;
      tableData.value = res.data.rows.length ? res.data.rows : [];
    } else {
      // 分页总数
      pagination.value.total = 0;
      tableData.value = [];
    }
  }).catch(err => {
    console.log(err);
  });*/
};
// 重置
const onRest = () => {
  proxy.resetForm("queryRef");

  proxy.$refs['mapRefQHT'].clearQHTMapQX();
  currentGemo.value=null;
  searchGemo.value=null;
  lastSearchParams.value=null;
  // 注意：切换tab时，要将页码显示到第一页，每页显示行数默认为10条
  pagination.value.pageNo = 1;
  pagination.value.pageSize = 10;

  if(activeName.value=="fourth"&&isRefesh.value) {
    isRefesh.value=false;
    proxy.$refs['mapRefQHT'].switchTabQHTMap();
  }

  // 加载表格
  if(activeName.value=="first"||activeName.value=="second"||activeName.value=="third") {
    onSearch();//todo:复制一个新的方法，与按钮操作区分开。
  }
};
// 导出
const onExport = () => {
  downloadGet('/groundMotionParameters/exportData', { ...params.value }, '地震动参数信息.xls');
}
// 新设
const onAdd = row => {
  router.push({ path: '/groundMotionParamManage/queryDetails', query: { type: 'add' } });
}

//地图传参--start
const mapDataList = ref([]);//地图圈选查询结果列表
//地图圈选查询
const getResultsByGeomText = (geomText) => {
  if(geomText!=null && geomText!=""){
    currentGemo.value=geomText;
    getListAndMapData();

    /*const query = {
      // ...params.value,
      geom: geomText,
    }
    mapLoading(true);
    //地图圈选查询
    queryResultsByGeomText(query).then((res) => {
      if (res.code === 200) {
        mapDataList.value = res.data;
        if(res.data!=null && res.data.length>0){
          let length = res.data.length;
          proxy.$modal.msgSuccess("查询到"+length+"条数据.");
        }else{
          proxy.$modal.msgWarning('圈选范围无查询结果！');
        }
      }else{
        proxy.$modal.msgWarning('查询失败！');
      }
      mapLoading(false);
    }).catch(err => {
      console.log(err);
      proxy.$modal.msgError('查询失败！');
      mapLoading(false);
    });*/
  }
};
//查询状态
const mapLoading = (bool) => {
  if(bool){
    proxy.$modal.loading("正在查询，请稍候...");
  }else{
    proxy.$modal.closeLoading();
  }
};
//地图传参--end

// 挂载完成
onMounted(() => {
  // 回显
  onSearch();
  // 获取行政区划数据
  getProvinceData();
});
</script>

<style lang="scss" scoped>
.form-location {
  .el-form-item {
    margin-right: 0;
  }

  .el-form-longitude,
  .el-form-latitude {
    width: 100px;
  }
}

.paging {
  padding: 20px 10%;
  .el-pagination{
    justify-content: center;
  }
}

.downloadModel {
  font-size: 16px;
  line-height: 60px;

  span {
    color: #107ce5;
    cursor: pointer;
  }
}
</style>